<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发票管理系统 - 发票统计</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
        }

        .sidebar {
            height: 100vh;
            background-color: #343a40;
            color: white;
            position: fixed;
            width: 250px;
            padding-top: 20px;
        }

            .sidebar .nav-link {
                color: rgba(255, 255, 255, 0.8);
                margin-bottom: 5px;
                border-radius: 5px;
                padding: 10px 15px;
            }

                .sidebar .nav-link:hover {
                    background-color: #495057;
                    color: white;
                }

                .sidebar .nav-link.active {
                    background-color: #007bff;
                    color: white;
                }

        .main-content {
            margin-left: 250px;
            padding: 20px;
        }

        .stat-card {
            margin-bottom: 20px;
            border-radius: 10px;
        }

        .stat-value {
            font-size: 2.5rem;
            font-weight: bold;
        }

        .chart-container {
            position: relative;
            height: 300px;
            margin-bottom: 20px;
        }

        .export-btn {
            margin-top: 20px;
        }

        .table-responsive {
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="text-center mb-4">
            <h4>发票管理系统</h4>
        </div>
        <ul class="nav flex-column">
            <li class="nav-item">
                <a class="nav-link" href="welcome.html">
                    <i class="bi bi-house-door me-2"></i>首页
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="upload.html">
                    <i class="bi bi-upload me-2"></i>发票上传
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="query.html">
                    <i class="bi bi-search me-2"></i>发票查询
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link active" href="statistic.html">
                    <i class="bi bi-bar-chart me-2"></i>发票统计
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#" id="logoutBtn">
                    <i class="bi bi-box-arrow-right me-2"></i>退出登录
                </a>
            </li>
        </ul>
    </div>

    <div class="main-content">
        <div class="container-fluid">
            <div class="row mb-4">
                <div class="col">
                    <h2>发票统计</h2>
                    <p class="text-muted">按日期范围或关键字统计发票数据</p>
                </div>
            </div>

            <div class="row">
                <div class="col">
                    <div class="card stat-card">
                        <div class="card-body">
                            <form id="statForm">
                                <div class="row">
                                    <div class="col-md-3">
                                        <div class="mb-3">
                                            <label for="statStartDate" class="form-label">开始日期</label>
                                            <input type="date" class="form-control" id="statStartDate">
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="mb-3">
                                            <label for="statEndDate" class="form-label">结束日期</label>
                                            <input type="date" class="form-control" id="statEndDate">
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="mb-3">
                                            <label for="statKeyword" class="form-label">关键字搜索</label>
                                            <input type="text" class="form-control" id="statKeyword" placeholder="输入发票类型、公司名称等">
                                        </div>
                                    </div>
                                    <div class="col-md-2 d-flex align-items-end">
                                        <button type="submit" class="btn btn-primary w-100">
                                            <i class="bi bi-calculator me-2"></i>统计
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-4">
                    <div class="card stat-card bg-primary text-white">
                        <div class="card-body text-center">
                            <h5 class="card-title">发票总数</h5>
                            <div class="stat-value" id="totalCount">0</div>
                            <p class="card-text">张</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card stat-card bg-success text-white">
                        <div class="card-body text-center">
                            <h5 class="card-title">合计金额</h5>
                            <div class="stat-value" id="totalAmount">0</div>
                            <p class="card-text">元</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card stat-card bg-info text-white">
                        <div class="card-body text-center">
                            <h5 class="card-title">平均金额</h5>
                            <div class="stat-value" id="averageAmount">0</div>
                            <p class="card-text">元/张</p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">发票类型分布</h5>
                            <div class="chart-container">
                                <canvas id="typeChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">月度金额趋势</h5>
                            <div class="chart-container">
                                <canvas id="monthlyTrendChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col">
                    <div class="card">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h5 class="card-title mb-0">销售方统计</h5>
                                <button id="exportBtn" class="btn btn-sm btn-outline-primary">
                                    <i class="bi bi-download me-2"></i>导出Excel
                                </button>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>销售方名称</th>
                                            <th>发票数量</th>
                                            <th>合计金额</th>
                                            <th>占比</th>
                                        </tr>
                                    </thead>
                                    <tbody id="sellerStatsTable">
                                        <!-- 数据将通过JavaScript动态加载 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
    <script>
        // 检查用户是否已登录
        const user_id = localStorage.getItem('user_id');
        if (!user_id) {
            window.location.href = 'index.html';
        }

        document.getElementById('logoutBtn').addEventListener('click', function () {
            localStorage.removeItem('user_id');
            window.location.href = 'index.html';
        });

        // 图表实例
        let typeChart, monthlyTrendChart;
        let currentStatsData = {};

        // 统计表单提交
        document.getElementById('statForm').addEventListener('submit', function (e) {
            e.preventDefault();
            getStatistics();
        });

        // 获取统计数据
        function getStatistics() {
            const startDate = document.getElementById('statStartDate').value;
            const endDate = document.getElementById('statEndDate').value;
            const keyword = document.getElementById('statKeyword').value;

            let url = `http://127.0.0.1:8080/api/statistics?user_id=${user_id}`;

            if (startDate && endDate) {
                url += `&start_date=${startDate}&end_date=${endDate}`;
            }

            if (keyword) {
                url += `&keyword=${encodeURIComponent(keyword)}`;
            }

            fetch(url)
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        alert(data.error);
                    } else {
                        // 更新基本统计信息
                        document.getElementById('totalCount').textContent = data.count || 0;
                        document.getElementById('totalAmount').textContent = data.total_amount ? parseFloat(data.total_amount).toFixed(2) : '0.00';

                        const avgAmount = data.count > 0 ? (data.total_amount / data.count) : 0;
                        document.getElementById('averageAmount').textContent = avgAmount.toFixed(2);

                        // 获取详细统计数据
                        getDetailedStatistics(startDate, endDate, keyword);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('获取统计数据失败，请稍后再试');
                });
        }

        // 获取详细统计数据
        function getDetailedStatistics(startDate, endDate, keyword) {
            let url = `http://127.0.0.1:8080/api/query?user_id=${user_id}`;

            if (startDate && endDate) {
                url += `&start_date=${startDate}&end_date=${endDate}`;
            }

            if (keyword) {
                url += `&keyword=${encodeURIComponent(keyword)}`;
            }

            fetch(url)
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        alert(data.error);
                    } else {
                        currentStatsData = data;
                        updateCharts(data.invoices);
                        updateSellerStats(data.invoices);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('获取详细数据失败，请稍后再试');
                });
        }

        // 更新图表
        function updateCharts(invoices) {
            // 发票类型分布
            const typeCounts = {};
            invoices.forEach(invoice => {
                const type = invoice.invoice_type || '其他';
                typeCounts[type] = (typeCounts[type] || 0) + 1;
            });

            const typeLabels = Object.keys(typeCounts);
            const typeData = Object.values(typeCounts);

            if (typeChart) {
                typeChart.destroy();
            }

            const typeCtx = document.getElementById('typeChart').getContext('2d');
            typeChart = new Chart(typeCtx, {
                type: 'pie',
                data: {
                    labels: typeLabels,
                    datasets: [{
                        data: typeData,
                        backgroundColor: [
                            '#4e73df',
                            '#1cc88a',
                            '#36b9cc',
                            '#f6c23e',
                            '#e74a3b',
                            '#858796'
                        ],
                        hoverBackgroundColor: [
                            '#2e59d9',
                            '#17a673',
                            '#2c9faf',
                            '#dda20a',
                            '#be2617',
                            '#6c757d'
                        ],
                        hoverBorderColor: "rgba(234, 236, 244, 1)",
                    }]
                },
                options: {
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'right'
                        },
                        tooltip: {
                            callbacks: {
                                label: function (context) {
                                    const label = context.label || '';
                                    const value = context.raw || 0;
                                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                    const percentage = Math.round((value / total) * 100);
                                    return `${label}: ${value} (${percentage}%)`;
                                }
                            }
                        }
                    }
                }
            });

            // 月度金额趋势
            const monthlyData = {};
            invoices.forEach(invoice => {
                if (invoice.invoice_date) {
                    const date = new Date(invoice.invoice_date);
                    const month = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}`;
                    monthlyData[month] = (monthlyData[month] || 0) + parseFloat(invoice.total_amount || 0);
                }
            });

            const sortedMonths = Object.keys(monthlyData).sort();
            const monthlyLabels = sortedMonths;
            const monthlyAmounts = sortedMonths.map(month => monthlyData[month]);

            if (monthlyTrendChart) {
                monthlyTrendChart.destroy();
            }

            const trendCtx = document.getElementById('monthlyTrendChart').getContext('2d');
            monthlyTrendChart = new Chart(trendCtx, {
                type: 'line',
                data: {
                    labels: monthlyLabels,
                    datasets: [{
                        label: '金额',
                        data: monthlyAmounts,
                        backgroundColor: 'rgba(78, 115, 223, 0.05)',
                        borderColor: 'rgba(78, 115, 223, 1)',
                        pointBackgroundColor: 'rgba(78, 115, 223, 1)',
                        pointBorderColor: '#fff',
                        pointHoverBackgroundColor: '#fff',
                        pointHoverBorderColor: 'rgba(78, 115, 223, 1)',
                        tension: 0.3
                    }]
                },
                options: {
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: function (value) {
                                    return '¥' + value.toFixed(2);
                                }
                            }
                        }
                    },
                    plugins: {
                        tooltip: {
                            callbacks: {
                                label: function (context) {
                                    return '¥' + context.raw.toFixed(2);
                                }
                            }
                        }
                    }
                }
            });
        }

        // 更新销售方统计表格
        function updateSellerStats(invoices) {
            const sellerStats = {};
            let totalAmount = 0;

            invoices.forEach(invoice => {
                const seller = invoice.seller_name || '未知销售方';
                const amount = parseFloat(invoice.total_amount || 0);

                if (!sellerStats[seller]) {
                    sellerStats[seller] = {
                        count: 0,
                        amount: 0
                    };
                }

                sellerStats[seller].count++;
                sellerStats[seller].amount += amount;
                totalAmount += amount;
            });

            // 转换为数组并排序
            const sellerArray = Object.keys(sellerStats).map(seller => {
                return {
                    name: seller,
                    count: sellerStats[seller].count,
                    amount: sellerStats[seller].amount,
                    percentage: totalAmount > 0 ? (sellerStats[seller].amount / totalAmount * 100) : 0
                };
            }).sort((a, b) => b.amount - a.amount);

            // 更新表格
            const tableBody = document.getElementById('sellerStatsTable');
            tableBody.innerHTML = '';

            sellerArray.forEach(seller => {
                const row = document.createElement('tr');
                row.innerHTML = `
                        <td>${seller.name}</td>
                        <td>${seller.count}</td>
                        <td>¥${seller.amount.toFixed(2)}</td>
                        <td>${seller.percentage.toFixed(1)}%</td>
                    `;
                tableBody.appendChild(row);
            });
        }

        // 导出Excel
        document.getElementById('exportBtn').addEventListener('click', function () {
            if (!currentStatsData.invoices || currentStatsData.invoices.length === 0) {
                alert('没有数据可导出');
                return;
            }

            // 准备数据
            const data = [
                ['发票号码', '开票日期', '销售方', '购买方', '金额', '合计金额', '发票类型']
            ];

            currentStatsData.invoices.forEach(invoice => {
                data.push([
                    invoice.invoice_number || '',
                    invoice.invoice_date || '',
                    invoice.seller_name || '',
                    invoice.buyer_name || '',
                    invoice.amount ? parseFloat(invoice.amount).toFixed(2) : '0.00',
                    invoice.total_amount ? parseFloat(invoice.total_amount).toFixed(2) : '0.00',
                    invoice.invoice_type || ''
                ]);
            });

            // 创建工作簿
            const wb = XLSX.utils.book_new();
            const ws = XLSX.utils.aoa_to_sheet(data);
            XLSX.utils.book_append_sheet(wb, ws, '发票数据');

            // 生成文件名
            const startDate = document.getElementById('statStartDate').value || '全部';
            const endDate = document.getElementById('statEndDate').value || '全部';
            const keyword = document.getElementById('statKeyword').value || '';
            let fileName = `发票统计_${startDate}_至_${endDate}`;
            if (keyword) {
                fileName += `_关键词_${keyword}`;
            }
            fileName += '.xlsx';

            // 导出文件
            XLSX.writeFile(wb, fileName);
        });

        // 页面加载时只初始化日期输入框，但不自动统计
        window.addEventListener('load', function () {
            const endDate = new Date();
            const startDate = new Date();
            startDate.setDate(endDate.getDate() - 30);

            document.getElementById('statStartDate').valueAsDate = startDate;
            document.getElementById('statEndDate').valueAsDate = endDate;

            // 初始化时显示0值
            document.getElementById('totalCount').textContent = '0';
            document.getElementById('totalAmount').textContent = '0.00';
            document.getElementById('averageAmount').textContent = '0.00';
        });
    </script>
</body>
</html>